#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <cerrno>
#include <cstring>
#include <sys/epoll.h>
#include "Err.hpp"
#include "Sock.hpp"
#include "LogMessage.hpp"

namespace epoll_ns
{
    using func_t = std::function<std::string(const std::string)>;

    static const uint16_t defaultport = 8080;
    static const int defaultfd = -1;
    static const int size = 128; // 这个size只需要大于0就行，因为在后面的linux中这个size由OS自动分配
    static const int defaultnum = 4096;
    static const int buffer_num = 1024;
    class EpollServer
    {
    public:
        EpollServer(func_t f, uint16_t port = defaultport, int num = defaultnum, int fd = defaultfd, int epollfd = defaultfd)
            :_func(f),  _port(port), _num(num), _listensock(fd), _epollfd(epollfd), _revs(nullptr)
        {
        }
        ~EpollServer()
        {
            if (_listensock != defaultfd)
                close(_listensock);
            if (_epollfd != defaultfd)
                close(_epollfd);
            if (_revs != nullptr)
                delete[] _revs;
        }

    public:
        void initServer()
        {
            _listensock = Sock::Socket();
            if (_listensock < 0)
            {
                logMessage(FATAL, "socket create error");
                exit(SOCK_ERR);
            }
            if (!Sock::Bind(_port, _listensock))
            {
                logMessage(FATAL, "socket bind error: %s", strerror(errno));
                exit(BIND_ERR);
            }
            if (!Sock::Listen(_listensock))
            {
                logMessage(FATAL, "socket listen error: %s", strerror(errno));
                exit(LISTEN_ERR);
            }
            // 1、先创建对应的epoll模型: epoll_create
            _epollfd = epoll_create(size);
            if (_epollfd == -1)
            {
                logMessage(FATAL, "epoll create failed, code: %d, errstring: %s", errno, strerror(errno));
                exit(EPOLL_CRT);
            }
            // 2、再将要等待的事件放入epoll对应的红黑树中: epoll_ctl，这里先将监听套接字放到epoll中
            struct epoll_event ev;
            ev.data.fd = _listensock;
            ev.events = EPOLLIN;
            epoll_ctl(_epollfd, EPOLL_CTL_ADD, _listensock, &ev);
            // 3、为就绪事件申请空间
            _revs = new struct epoll_event[_num];
        }
        void start()
        {
            // 3、将红黑树上的事件放入到等待队列中: epoll_wait
            int timeout = -1; // 单位: ms
            for (;;)
            {
                int n = epoll_wait(_epollfd, _revs, _num, timeout);
                switch (n)
                {
                case 0: // 超时
                    logMessage(NORMAL, "time out......");
                    break;
                case -1: // epoll_wait调用失败
                    logMessage(ERROR, "epoll_wait error, code: %d, errstring: %s", errno, strerror(errno));
                    break;
                default: // 事件就绪
                    HandlerEvents(n);
                    break;
                }
            }
        }

    public:
        void HandlerEvents(int n)
        {
            for (int i = 0; i < n; i++)
            {
                if (_revs[i].data.fd == _listensock && (_revs[i].events & EPOLLIN))
                    Accepter();
                else if (_revs[i].events & EPOLLIN)
                    Recver(_revs[i].data.fd);
                else
                {
                    // bug?
                }
            }
            // Print(n);
        }
        void Accepter()
        {
            uint16_t clientport;
            std::string clientip;
            logMessage(NORMAL, "get a new link......");
            int sock = Sock::Accept(_listensock, &clientip, &clientport);
            if (sock < 0)
            {
                logMessage(NORMAL, "connection failed......");
                return;
            }
            logMessage(NORMAL, "connection success:[%s: %d]", clientip.c_str(), clientport);
            struct epoll_event ev;
            ev.data.fd = sock;
            ev.events = EPOLLIN;
            epoll_ctl(_epollfd, EPOLL_CTL_ADD, sock, &ev);
        }
        void Recver(int sock)
        {
            char buffer[buffer_num];
            int n = recv(sock, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                logMessage(NORMAL, "client# %s", buffer);

                std::string resp = _func(buffer);
                send(sock, resp.c_str(), resp.size(), 0);
            }
            else if (n == 0)
            {
                // 先将该fd从红黑树上删除，因为假如先关闭fd，那么调用epoll_ctl来删除该节点的时候
                // 这个fd就是一个非法的fd，可能会导致调用的失败
                epoll_ctl(_epollfd, EPOLL_CTL_DEL, sock, nullptr); // 删除的时候，最后一个参数会被忽略
                close(sock);
                logMessage(NORMAL, "client quit......");
                return;
            }
            else
            {
                epoll_ctl(_epollfd, EPOLL_CTL_DEL, sock, nullptr); // 删除的时候，最后一个参数会被忽略
                close(sock);
                logMessage(NORMAL, "recv failed, code: %d, errstring: %s", errno, strerror(errno));
                return;
            }
        }
        // void Print(int num)
        // {
        //     std::cout << "fd list: " ;
        //     for(int i = 0; i < num; i++)
        //     {
        //         std::cout << _revs[i].data.fd << " ";
        //     }
        //     std::cout << std::endl;
        // }
    private:
        uint16_t _port;
        int _listensock;
        int _epollfd;
        int _num;
        struct epoll_event *_revs;
        func_t _func;
    };
}